package com.openlogic.common.logic.run;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.event.AppBeanLoadEndEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.openlogic.common.core.utils.DateUtils;
import com.openlogic.common.logic.constants.RuleConstants;
import com.openlogic.common.logic.node.enums.NodeExecEnums;
import com.openlogic.common.logic.node.factory.NodeExecFactory;
import com.openlogic.common.logic.utils.CommUtils;
import com.openlogic.common.logic.utils.StackExceptionUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
* @ClassName: ExecCommNodeHandler
* @Description: 通信节点运行执行器
* @author weiyongpeng
* @date 2024年7月17日 上午9:12:36
 */
@Component
public class ExecCommNodeHandler extends ExecRuleHandler{
	
	private static final Logger logger = LoggerFactory.getLogger(ExecCommNodeHandler.class);

	@Override
	public JSONObject typeRun(JSONArray resultArray1,JSONArray nodeArray,JSONArray lineArray,JSONObject inputjson,JSONArray areaArray,String areaFirst,String ruleId,StringBuffer reason,Map<String,Object> map) {
		JSONObject reJson = new JSONObject();
		logger.info("CommNode Begin Run Starting...");
		// 默认节点解析后的数据
		logger.info("typeRun=====" +  resultArray1.toString());
		reJson = recRunForNode(resultArray1,nodeArray,lineArray,inputjson,areaArray,areaFirst,ruleId,reason,map);	
		return reJson;
	}

	/**
	* 描述：迭代节点执行
	* @Title: recRunForDefault
	* @param resultArray1
	* @param nodeArray
	* @param lineArray
	* @param inputjson
	* @param areaArray
	* @param areaFirst
	* @param ruleId
	* @param reason
	* @param map
	* @return
	* @author weiyongpeng
	* @date  2024年7月17日 上午10:29:23
	 */
	@Override
	protected JSONObject recRunForNode(JSONArray resultArray1, JSONArray nodeArray, JSONArray lineArray,
			JSONObject inputjson, JSONArray areaArray, String areaFirst, String ruleId, StringBuffer reason,
			Map<String, Object> map) {
		// 开始执行时间
		Date startDate = DateUtils.getNowDate();
		String startExecuateTime = DateUtils.formatDate(startDate, DateUtils.YYYY_MM_DD_HH_MM_SS);
		
		// 异常信息
		String errorMsg = "";
		// 流程执行结束的json对象
		JSONObject reJson = new JSONObject();
		// 发生异常的时候返回的json对象
		JSONObject errorJson = new JSONObject();
		// 下一个可执行节点的json对象
		JSONObject nextResult = new JSONObject();
		
		try {
			//那么
			String successString = ((JSONObject)resultArray1.get(3)).get("success").toString();
			// url=http://localhost:8080/RuleISSUE/hessian/HessianService&@commType=hessian&@functionName=queryResult&@resultId=917fe25e8bd342ba8cad6453bac8ba71&@user=admin&@password=1&@inputOut=res&@
			String[] succlist =  successString.split("&@");
			//访问地址
			String url = succlist[0].split("=")[1];
			//通讯类型
			String commType = succlist[1].split("=")[1];
			//方法名称/请求方式 如果是http协议则不需要方法名称
			String reqType = ""; 
			String functionName = "";
			if(commType.equals("http")) {
				reqType = succlist[2].split("=")[1];
			}else {
				functionName = succlist[2].split("=")[1];
			}
			//返回参数
			String resultlist = succlist[succlist.length-1].split("=")[1];
			//入参
			String params = commType.equals("http") && reqType.equals("post") ? "{" : "";
			//wbservice格式的入参
			Object[] wsParams = new Object[succlist.length-4];
			//如果是Http方式需要获取请求方式
			for(int x=3, i = 0,succlistlength=succlist.length;x<succlistlength-1;x++,i++) {
				if(commType.equals("http") && reqType.equals("get")) {
					if(x==3) {
						params+=succlist[x];
					}else {
						params+="&"+succlist[x];
					}
				}if(commType.equals("http") && reqType.equals("post")) {
					params += "\"" + succlist[x].split("=")[0] + "\"" + ":" + "\"" + succlist[x].split("=")[1] + "\"" +  ",";
				}else if(commType.equals("webService")){
					wsParams[i] = succlist[x].split("=")[1];
				}else {
					if(x==3) {
						params+=succlist[x];
					}else {
						params+=","+succlist[x];
					}
				}
			}
			//返回值
			String commResult="";
			try {
				//通讯方法
		    	commResult = CommUtils.comm(url, commType, functionName, params, reqType, wsParams);
		        // logger.info(commResult);
			} catch (Exception e) {
				errorMsg = StackExceptionUtils.getExceptionType(e).toString();
				logger.error("异常信息:{}",e.getMessage());
			}
			JSONObject jsonObject = JSONObject.fromObject(commResult);
			String[] resultslist = resultlist.split(",");
			for(int y=0;y<resultslist.length;y++) {
				if(jsonObject.get(resultslist[y])!=null){ 
					inputjson.put(resultslist[y], jsonObject.get(resultslist[y]));
				}
			}
		} catch (Exception e) {
			errorMsg = StackExceptionUtils.getExceptionType(e).toString();
			logger.error("异常信息:{}",e.getMessage());
		}

		if (errorMsg == null || errorMsg.equals("")) {
			reJson = inputjson;
			if(resultArray1.get(2).equals("area")) {
				if(areaFirst.equals("")) {//判断是否是循环的第一个 节点
					areaFirst = resultArray1.getString(0);
					reJson.put("areaFirst", areaFirst);
				}
			}
			nextResult = runNextNode(resultArray1,nodeArray,lineArray,inputjson,areaArray,areaFirst,ruleId,0,reason,map,startDate,null,null);
			if(!nextResult.toString().equals("{}")) {
				return nextResult;
			}
		}else {
			Map<Object,Object> errorMap = new HashMap<>();
			errorMap.put("msg", errorMsg);
			errorJson = JSONObject.fromObject(errorMap);
			// 执行异常信息
			nextResult = runNextNodeThrow(resultArray1,nodeArray,lineArray,inputjson,areaArray,areaFirst,ruleId,0,reason,map,startDate,null,errorJson);
			if(!nextResult.toString().equals("{}")) {
				return nextResult;
			}
		}
		// 结束执行时间
		Date endDate = DateUtils.getNowDate();
		String endExecuateTime = DateUtils.formatDate(endDate, DateUtils.YYYY_MM_DD_HH_MM_SS);
		reJson.put("startExecTime", startExecuateTime);
		reJson.put("endExecTime", endExecuateTime);
		reJson.put("execTotalTimeMills", "耗时: "+(endDate.getTime() - startDate.getTime())+" 毫秒");
		reJson.put("execStatus", RuleConstants.NODE_EXEC_SUCCESS);
		return reJson;
	}
	
	@Override
	public void onEvent(AppBeanLoadEndEvent event) throws Throwable {
		NodeExecFactory.register(NodeExecEnums.COMMON_NODE.getCode(), this);
	}

}
